package com.example.retrofitdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class YouDaoActivity extends AppCompatActivity {
    private static final String TAG = "JinShanCiBaActivity";
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_youdao);
        tv = findViewById(R.id.tv);
        request();
    }

    /**
     * 请求网络
     */
    private void request() {
        // 步骤4，创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://fanyi.youdao.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        // 步骤5，创建网络请求接口实例
        YouDao_Interface request = retrofit.create(YouDao_Interface.class);

        // 对发送请求进行封装
        Call<Translate2> call = request.getCall("I Love you");

        // 步骤6，发送网络请求（异步）
        call.enqueue(new Callback<Translate2>() {
            @Override
            public void onResponse(Call<Translate2> call, Response<Translate2> response) {
                // 步骤7：处理返回的数据结果
                Translate2 translate = response.body();
                tv.setText(translate.translateResult.get(0).get(0).tgt);
            }

            @Override
            public void onFailure(Call<Translate2> call, Throwable t) {
                Log.e(TAG, "onFailure: ");
            }
        });
    }
}
